import {Extension} from './extension';
import type { DarkModeSettings } from '@/entrypoints/core/darkMode';

export default defineBackground(() => {
  console.log('Dark Reader Clone background script loaded');

  // 存储所有连接的端口
  const ports: { [tabId: number]: browser.runtime.Port } = {};

  // 监听来自内容脚本的连接
  browser.runtime.onConnect.addListener((port) => {
    console.log('New connection from content script');
    const tabId = port.sender?.tab?.id;
    if (tabId) {
      ports[tabId] = port;
      port.onDisconnect.addListener(() => {
        delete ports[tabId];
      });
    }
  });

  // 监听来自弹出窗口的消息
  browser.runtime.onMessage.addListener((message, sender) => {
    if (message.type === 'updateDarkMode') {
      console.log('Background received updateDarkMode message:', message);
      // 向所有连接的内容脚本广播消息
      Object.values(ports).forEach((port) => {
        port.postMessage(message);
      });
    }
  });
});
